package com.lill.common.component.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
	
	public static String sendGet(String url) {
        String result = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");
            connection.setRequestProperty("Content-Type", "plain/text; charset=UTF-8");
            connection.setRequestMethod("GET");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            if(connection.getResponseCode()<300)
            	result=StreamUtil.inputStream2String(connection.getInputStream());
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return result;
    }
	
    public static String sendPost(String url, String jsonParam) {
    	OutputStream out= null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置Content-Type
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out=conn.getOutputStream();
            // 发送请求参数
            out.write(jsonParam.getBytes());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            if(conn.getResponseCode()<300)
            	result=StreamUtil.inputStream2String(conn.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
        	try {
				if(out!=null) out.close();
			} catch (IOException e) {}
        }
        return result;
    }
}
